import React, { useReducer, useEffect, useState } from "react";
import { Alert } from "react-native";
import query from "../../api/query";
import { fileWeb } from "../../api/query";
import axios from "axios";
import AsyncStorage from "@react-native-async-storage/async-storage";

const InterviewContext = React.createContext();

// const initData = [
//   {
//     _id: 1,
//     fileName: "sd-001-01-01-TP001",
//     type: "市级访谈",
//     provincekey: "610000",
//     citykey: "610100",
//     areakey: "610116",
//     province: "陕西省",
//     city: "西安市",
//     area: "长安区",
//     address: "西长安街620号陕西师范大学长安校区",
//     latitude: "",
//     longitude: "",
//     municipalLeaders: 0,
//     municipalDepartment: 8,
//     countyLeaders: 4,
//     countyDepartment: 9,
//     townshipLeaders: 6,
//     villageCadres: 7,
//     villageDoctorsAndPrincipals: 2,
//     firstSecretary: 1,
//     NPCdeputies: 5,
//     interviewImageList: [
//       "https://tenfei04.cfp.cn/creative/vcg/nowater800/new/VCG211284905032.jpg?x-oss-process=image/format,webp",
//       "https://alifei02.cfp.cn/creative/vcg/nowater800/new/VCG211276212429.jpg?x-oss-process=image/format,webp",
//       "https://alifei03.cfp.cn/creative/vcg/nowater800/new/VCG211387674518.jpg?x-oss-process=image/format,webp",
//     ],
//     interviewAudioList: [
//       {
//         name: "测试4.aac",
//         uri: "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Fapp-client-6476f2ce-d15f-4a42-8cd5-a02dbac394a1/DocumentPicker/e8205058-80a6-4480-aef8-e37328efda62.aac",
//       },
//       {
//         name: "测试2.aac",
//         uri: "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Fapp-client-6476f2ce-d15f-4a42-8cd5-a02dbac394a1/DocumentPicker/e642f010-2c4b-48a8-b47c-d2cbf8558a03.aac",
//       },
//     ],
//     interviewVideoList: [
//       "https://gossv.cfp.cn/videos/mts_videos/medium/VCG2219829293.mp4",
//       "https://gossv.cfp.cn/videos/mts_videos/preview/VCG2219685073.mp4",
//     ],
//     time: "2022-10-6 下午12:51",
//     publisher: "李艳婷",
//     group: "1",
//   },
//   {
//     _id: 2,
//     fileName: "sd-001-01-01-BY001",
//     type: "县级访谈",
//     provincekey: "610000",
//     citykey: "610400",
//     areakey: "610404",
//     province: "陕西省",
//     city: "咸阳市",
//     area: "渭城区",
//     address: "渭柳佳苑",
//     latitude: "",
//     longitude: "",
//     municipalLeaders: 3,
//     municipalDepartment: 18,
//     countyLeaders: 2,
//     countyDepartment: 5,
//     townshipLeaders: 9,
//     villageCadres: 3,
//     villageDoctorsAndPrincipals: 0,
//     firstSecretary: 1,
//     NPCdeputies: 2,
//     interviewImageList: [
//       "https://tenfei03.cfp.cn/creative/vcg/nowarter800/new/VCG41600204758.jpg?x-oss-process=image/format,webp",
//       "https://tenfei02.cfp.cn/creative/vcg/nowater800/new/VCG21gic5475777.jpg?x-oss-process=image/format,webp",
//     ],
//     interviewAudioList: [],
//     interviewVideoList: [
//       "https://gossv.cfp.cn/videos/mts_videos/preview/VCG2219918847.mp4",
//       "https://gossv.cfp.cn/videos/mts_videos/preview/VCG2219809383.mp4",
//     ],
//     time: "2022-10-7 上午11:23",
//     publisher: "刘盼盼",
//     group: "1",
//   },
//   {
//     _id: 3,
//     fileName: "sd-001-01-01-YB001",
//     type: "市级访谈",
//     provincekey: "610000",
//     citykey: "610100",
//     areakey: "610113",
//     province: "陕西省",
//     city: "西安市",
//     area: "雁塔区",
//     address: "陕西师范大学雁塔校区",
//     latitude: "",
//     longitude: "",
//     municipalLeaders: 9,
//     municipalDepartment: 8,
//     countyLeaders: 3,
//     countyDepartment: 9,
//     townshipLeaders: 5,
//     villageCadres: 7,
//     villageDoctorsAndPrincipals: 9,
//     firstSecretary: 2,
//     NPCdeputies: 5,
//     interviewImageList: [
//       "https://alifei05.cfp.cn/creative/vcg/nowater800/new/VCG211280808171.jpg?x-oss-process=image/format,webp",
//       "https://alifei02.cfp.cn/creative/vcg/nowater800/new/VCG211304746158.jpg?x-oss-process=image/format,webp",
//     ],
//     interviewAudioList: [],
//     interviewVideoList: [
//       "https://gossv.cfp.cn/videos/mts_videos/preview/VCG2215910509.mp4",
//       "https://gossv.cfp.cn/videos/mts_videos/preview/VCG2219787170.mp4",
//     ],
//     time: "2022-10-1 下午3:47",
//     publisher: "曾憨憨",
//     group: "1",
//   },
//   {
//     _id: 4,
//     fileName: "sd-001-01-02-TP002",
//     type: "市级访谈",
//     provincekey: "610000",
//     citykey: "610300",
//     areakey: "610330",
//     province: "陕西省",
//     city: "宝鸡市",
//     area: "凤县",
//     address: "北杨村",
//     latitude: "",
//     longitude: "",
//     municipalLeaders: 0,
//     municipalDepartment: 5,
//     countyLeaders: 7,
//     countyDepartment: 8,
//     townshipLeaders: 3,
//     villageCadres: 0,
//     villageDoctorsAndPrincipals: 3,
//     firstSecretary: 5,
//     NPCdeputies: 5,
//     interviewImageList: [
//       "https://alifei02.cfp.cn/creative/vcg/nowarter800/new/VCG211135282609.jpg?x-oss-process=image/format,webp",
//       "https://tenfei03.cfp.cn/creative/vcg/nowarter800/new/VCG41N1169250112.jpg?x-oss-process=image/format,webp",
//     ],
//     interviewAudioList: [],
//     interviewVideoList: [
//       "https://gossv.cfp.cn/videos/mts_videos/preview/VCG2219780907.mp4",
//       "https://gossv.cfp.cn/videos/mts_videos/preview/VCG2219821862.mp4",
//     ],
//     time: "2022-10-3 上午11:28",
//     publisher: "张老师",
//     group: "1",
//   },
//   {
//     _id: 5,
//     fileName: "sd-001-01-02-YB002",
//     type: "村级访谈",
//     provincekey: "610000",
//     citykey: "610600",
//     areakey: "610630",
//     province: "陕西省",
//     city: "延安市",
//     area: "宜川县",
//     address: "陈家庄村",
//     latitude: "",
//     longitude: "",
//     municipalLeaders: 10,
//     municipalDepartment: 5,
//     countyLeaders: 4,
//     countyDepartment: 7,
//     townshipLeaders: 3,
//     villageCadres: 6,
//     villageDoctorsAndPrincipals: 7,
//     firstSecretary: 2,
//     NPCdeputies: 5,
//     interviewImageList: [
//       "https://alifei03.cfp.cn/creative/vcg/nowarter800/version21/VCG21gic20084438.jpg?x-oss-process=image/format,webp",
//       "https://tenfei01.cfp.cn/creative/vcg/nowarter800/new/VCG21gic6409646.jpg?x-oss-process=image/format,webp",
//     ],
//     interviewAudioList: [],
//     interviewVideoList: [
//       "https://gossv.cfp.cn/videos/mts_videos/preview/VCG2218505746.mp4",
//       "https://gossv.cfp.cn/videos/mts_videos/preview/VCG2219809383.mp4",
//     ],
//     time: "2022-10-9 下午6:40",
//     publisher: "访谈小队",
//     group: "1",
//   },
// ];

const dataReducer = (state, action) => {
  switch (action.type) {
    case "fetch_init":
      return action.payload;
    case "add_interview":
      return [...state, action.payload];
    case "edit_interview":
      return state.map((item) => {
        return item._id === action.payload._id ? action.payload : item;
      });
    case "delete_interview":
      return state.filter((item) => item._id !== action.payload);
    default:
      return state;
  }
};

export const InterviewProvider = ({ children }) => {
  const [InterviewList, dispatch] = useReducer(dataReducer, []);
  const [isInterviewLoading, setIsInterviewLoading] = useState(false);
  const [isInterviewError, setIsInterviewError] = useState(false);

  useEffect(() => {
    //TODO:出错处理有待改进
    const fetchData = async () => {
      setIsInterviewLoading(true);
      setIsInterviewError(false);
      try {
        const role = await AsyncStorage.getItem("role");
        const token = await AsyncStorage.getItem("token");
        let result = [];
        if (role === "user") {
          result = await query.get("/interview/user/", {
            headers: { Authorization: token },
          });
        } else if (role == "admin") {
          result = await query.get("/interview/group/", {
            headers: { Authorization: token },
          });
        } else {
          result = await query.get("/interview/", {
            headers: { Authorization: token },
          });
        }
        dispatch({ type: "fetch_init", payload: result.data.data });
      } catch (err) {
        setIsInterviewError(true);
        console.log(err);
      }
      setIsInterviewLoading(false);
    };
    fetchData();
  }, []);

  const deleteInterview = async (deleteData, setIsLoading) => {
    try {
      if (
        deleteData.interviewImageList.length != 0 ||
        deleteData.interviewVideoList.length != 0 ||
        deleteData.interviewAudioList.length != 0
      ) {
        //将图片、视频、录音从本地服务器删掉
        let idGroup = [];
        if (deleteData.interviewImageList.length != 0) {
          let imageidGroup = deleteData.interviewImageList.map((item) => {
            return item._id;
          });
          idGroup = [...idGroup, ...imageidGroup];
        }
        if (deleteData.interviewVideoList.length != 0) {
          let videoidGroup = deleteData.interviewVideoList.map((item) => {
            return item._id;
          });
          idGroup = [...idGroup, ...videoidGroup];
        }
        if (deleteData.interviewAudioList.length != 0) {
          let audioidGroup = deleteData.interviewAudioList.map((item) => {
            return item._id;
          });
          idGroup = [...idGroup, ...audioidGroup];
        }
        await axios.delete(fileWeb + "/upload/multi", { data: idGroup });
      }
      //调用后端接口进行删除
      const token = await AsyncStorage.getItem("token");
      await query.delete("/interview/" + deleteData._id, {
        headers: { Authorization: token },
      });
      //处理前端数据
      dispatch({ type: "delete_interview", payload: deleteData._id });
      setIsLoading();
      Alert.alert("", "删除成功");
    } catch (err) {
      console.log("删除访谈出错", err);
      setIsLoading();
      Alert.alert("", "删除失败");
    }
  };

  const addInterview = async (addData, callback, setIsLoading) => {
    try {
      //将图片、视频、录音保存在本地文件服务器
      if (
        addData.interviewImageList.length != 0 ||
        addData.interviewVideoList.length != 0 ||
        addData.interviewAudioList.length != 0
      ) {
        let formData = new FormData();
        if (addData.interviewImageList.length != 0) {
          addData.interviewImageList.forEach((item) => {
            formData.append("files", {
              name: item.split("/").pop(),
              uri: item,
              type: "image/" + item.split(".").pop(),
            });
          });
        }
        if (addData.interviewVideoList.length != 0) {
          addData.interviewVideoList.forEach((item) => {
            formData.append("files", {
              name: item.split("/").pop(),
              uri: item,
              type: "video/" + item.split(".").pop(),
            });
          });
        }
        if (addData.interviewAudioList.length != 0) {
          addData.interviewAudioList.forEach((item) => {
            formData.append("files", {
              name: item.uri.split("/").pop(),
              uri: item.uri,
              type: "audio/" + item.uri.split(".").pop(),
            });
          });
        }
        let res = await fetch(fileWeb + "/upload/multi", {
          method: "post",
          headers: {
            "Content-Type": "multipart/form-data",
          },
          body: formData,
        });
        let response = await res.json();
        addData.interviewImageList = response.message.filter(
          (item) => item.fileType.split("/").shift() == "image"
        );
        addData.interviewVideoList = response.message.filter(
          (item) => item.fileType.split("/").shift() == "video"
        );
        addData.interviewAudioList = response.message.filter(
          (item) => item.fileType.split("/").shift() == "audio"
        );
      }

      //调用后端接口进行添加
      const token = await AsyncStorage.getItem("token");
      const result = await query.post("/interview/", addData, {
        headers: { Authorization: token },
      });
      //后端返回数据更新前端
      dispatch({ type: "add_interview", payload: result.data.data });
      //成功后取消IsLoading,并返回上一页
      setIsLoading();
      Alert.alert("", "添加访谈成功", [
        {
          text: "确定",
          onPress: () => callback(),
        },
      ]);
    } catch (err) {
      //失败后取消IsLoading
      console.log(err);
      setIsLoading();
      Alert.alert("", "添加访谈失败");
    }
  };

  const editInterview = async (
    editData,
    originImages,
    deleteOriginImages,
    originAudio,
    deleteOriginAudio,
    originVideos,
    deleteOriginVideos,
    callback,
    setIsLoading
  ) => {
    try {
      if (
        editData.interviewImageList.length != 0 ||
        editData.interviewVideoList.length != 0 ||
        editData.interviewAudioList.length != 0 ||
        deleteOriginImages.length != 0 ||
        deleteOriginVideos.length != 0 ||
        deleteOriginAudio.length != 0 ||
        originImages.length != 0 ||
        originVideos.length != 0 ||
        originAudio.length != 0
      ) {
        //需新增图片、视频
        let formData = new FormData();
        if (editData.interviewImageList.length != 0) {
          editData.interviewImageList.forEach((item) => {
            formData.append("files", {
              name: item.split("/").pop(),
              uri: item,
              type: "image/" + item.split(".").pop(),
            });
          });
        }
        if (editData.interviewVideoList.length != 0) {
          editData.interviewVideoList.forEach((item) => {
            formData.append("files", {
              name: item.split("/").pop(),
              uri: item,
              type: "video/" + item.split(".").pop(),
            });
          });
        }
        if (editData.interviewAudioList.length != 0) {
          editData.interviewAudioList.forEach((item) => {
            formData.append("files", {
              name: item.uri.split("/").pop(),
              uri: item.uri,
              type: "audio/" + item.uri.split(".").pop(),
            });
          });
        }
        //需删除的原始图片、视频
        if (deleteOriginImages.length != 0) {
          deleteOriginImages.forEach((item) => {
            formData.append("idGroup[]", item._id);
          });
        }
        if (deleteOriginVideos.length != 0) {
          deleteOriginVideos.forEach((item) => {
            formData.append("idGroup[]", item._id);
          });
        }
        if (deleteOriginAudio.length != 0) {
          deleteOriginAudio.forEach((item) => {
            formData.append("idGroup[]", item._id);
          });
        }
        //需保留的原始图片、视频
        if (originImages.length != 0) {
          originImages.forEach((item) => {
            formData.append("origin[]", item._id);
          });
        }
        if (originVideos.length != 0) {
          originVideos.forEach((item) => {
            formData.append("origin[]", item._id);
          });
        }
        if (originAudio.length != 0) {
          originAudio.forEach((item) => {
            formData.append("origin[]", item._id);
          });
        }
        let res = await fetch(fileWeb + "/upload/multi", {
          method: "patch",
          headers: {
            "Content-Type": "multipart/form-data",
          },
          body: formData,
        });
        let response = await res.json();
        editData.interviewImageList = response.message.filter(
          (item) => item.fileType.split("/").shift() == "image"
        );
        editData.interviewVideoList = response.message.filter(
          (item) => item.fileType.split("/").shift() == "video"
        );
        editData.interviewAudioList = response.message.filter(
          (item) => item.fileType.split("/").shift() == "audio"
        );
      }
      //对后端进行修改
      const token = await AsyncStorage.getItem("token");
      const result = await query.patch("/interview/" + editData._id, editData, {
        headers: { Authorization: token },
      });
      //拿到后端返回的数据对前端进行修改
      dispatch({ type: "edit_interview", payload: result.data.data });
      //成功后取消IsLoading,并返回查看页面
      setIsLoading();
      Alert.alert("", "修改访谈信息成功", [
        {
          text: "确定",
          onPress: () => callback(),
        },
      ]);
    } catch (err) {
      //失败后取消IsLoading
      console.log("------------------", err);
      setIsLoading();
      Alert.alert("", "修改访谈信息失败");
    }
  };

  const deleteInterviewAndBack = async (deleteData, setIsLoading, setBack) => {
    try {
      //将图片、视频、录音从本地服务器删掉
      if (
        deleteData.interviewImageList.length != 0 ||
        deleteData.interviewVideoList.length != 0 ||
        deleteData.interviewAudioList.length != 0
      ) {
        let idGroup = [];
        if (deleteData.interviewImageList.length != 0) {
          let imageidGroup = deleteData.interviewImageList.map((item) => {
            return item._id;
          });
          idGroup = [...idGroup, ...imageidGroup];
        }
        if (deleteData.interviewVideoList.length != 0) {
          let videoidGroup = deleteData.interviewVideoList.map((item) => {
            return item._id;
          });
          idGroup = [...idGroup, ...videoidGroup];
        }
        if (deleteData.interviewAudioList.length != 0) {
          let audioidGroup = deleteData.interviewAudioList.map((item) => {
            return item._id;
          });
          idGroup = [...idGroup, ...audioidGroup];
        }
        await axios.delete(fileWeb + "/upload/multi", { data: idGroup });
      }
      //调用后端接口进行删除
      const token = await AsyncStorage.getItem("token");
      await query.delete("/interview/" + deleteData._id, {
        headers: { Authorization: token },
      });
      //处理前端数据
      dispatch({ type: "delete_interview", payload: deleteData._id });
      setIsLoading();
      setBack();
      Alert.alert("", "删除成功");
    } catch (err) {
      console.log("删除访谈出错", err);
      setIsLoading();
      Alert.alert("", "删除失败");
    }
  };

  return (
    <InterviewContext.Provider
      value={{
        interviewList: InterviewList,
        isInterviewLoading,
        isInterviewError,
        deleteInterview,
        deleteInterviewAndBack,
        addInterview,
        editInterview,
      }}
    >
      {children}
    </InterviewContext.Provider>
  );
};

export default InterviewContext;
